<template>
	<view class="spc-xr-chart">
		<!-- 均值图 -->
		<qiun-data-charts ref="meanChart" type="line" :opts="meanChartOpts" :ontouch="true" onzoom
			:chartData="meanChartData" @getIndex="onMeanChartIndex"></qiun-data-charts>

	</view>
</template>

<script>
	export default {
		name: "SpcJZChart",
		props: {
			data: {
				type: Array,
				required: true
			},
			spec: {
				type: Object,
				default: () => ({
					usl: null,
					lsl: null,
					target: null
				})
			}
		},
		data() {
			return {
				meanChartData: {},
				meanChartOpts: {
					legend: {
						show: false
					},
					xAxis: {
						disableGrid: true
					},
					yAxis: {}, // 会在 processData 中动态生成
					extra: {
						line: {
							type: "straight",
							animation: true,
							disableLegend: false
						},
						markLine: { // 标记线配置
							type: 'dash',
							data: [] // 会在 processData 中动态生成
						}
					}
				},
			};
		},
		// watch: {
		// 	data: {
		// 		handler(newVal) {
		// 			this.processData(newVal);
		// 		},
		// 		immediate: true
		// 	}
		// },
		mounted() {
			this.processData(this.data);
		},
		methods: {
			processData(data) {
				if (!data || data.length === 0) return;

				console.log(data);
				const xLabels = data.map((item, index) => index + 1);
				const meanValues = data.map(item => item.mean);


				const meanYAxisOptions = this.calculateMeanYAxisOptions(meanValues, this.spec);
				console.log(meanYAxisOptions);

				this.meanChartData = {
					categories: xLabels,
					series: [{
						name: " ",
						data: meanValues,
						color: "#1890FF"
					}]
				};
				let meanMarkLines = [];

				// 如果有USL/LSL/Target，添加到标记线
				if (this.spec.usl !== null) {
					meanMarkLines.push({
						labelText: 'USL=' + this.spec.usl.toFixed(3),
						value: this.spec.usl.toFixed(3),
						showLabel: true,
						labelAlign: 'right',
						lineColor: '#3fc314',
						labelFontColor: '#3fc314',
						labelBgOpacity: 0
					});
				}

				if (this.spec.lsl !== null) {
					meanMarkLines.push({
						labelText: 'LSL=' + this.spec.lsl.toFixed(3),
						value: this.spec.lsl.toFixed(3),
						showLabel: true,
						labelAlign: 'right',
						lineColor: '#3fc314',
						labelFontColor: '#3fc314',
						labelBgOpacity: 0
					});
				}

				if (this.spec.target !== null) {
					meanMarkLines.push({
						labelText: 'Target=' + this.spec.target.toFixed(3),
						value: this.spec.target.toFixed(3),
						showLabel: true,
						labelAlign: 'right',
						lineColor: '#3fc314',
						labelFontColor: '#3fc314',
						labelBgOpacity: 0
					});
				}

				// 更新均值图配置
				this.meanChartOpts = {
					enableScroll: true,
					padding: [20, 80, 0, 0],
					legend: {
						show: false,
					},
					xAxis: {
						scrollShow: true,
						itemCount: 6,
						disableGrid: true
					},
					yAxis: meanYAxisOptions,
					extra: {
						line: {
							type: "straight",
							animation: true,
							disableLegend: false
						},
						markLine: {
							type: 'dash',
							dashLength: 12,
							data: meanMarkLines
						}
					}
				};

			},


			// 计算均值图Y轴范围（严格使用USL/LSL作为边界）
			calculateMeanYAxisOptions(values, spec) {
				// 过滤无效值，避免计算错误
				const validValues = values.filter(val => typeof val === 'number' && !isNaN(val));
				if (validValues.length === 0) {
					return {
						format: val => val.toFixed(3),
						data: [{
							min: 0,
							max: 100,
							tofix: 2
						}] // 默认范围
					};
				}

				// 优先使用规格限，但增加缓冲带避免数据贴边
				let yMin = spec.lsl !== null ? spec.lsl : null;
				let yMax = spec.usl !== null ? spec.usl : null;

				// 计算数据实际波动范围
				const dataMin = Math.min(...validValues);
				const dataMax = Math.max(...validValues);
				const dataRange = dataMax - dataMin;
				const buffer = dataRange > 0 ? dataRange * 0.1 : 1; // 10%缓冲带，至少1单位

				// 处理规格限与实际数据的关系
				if (yMin !== null && yMax !== null) {
					// 确保数据完全显示在规格限内
					yMin = Math.min(yMin, dataMin - buffer);
					yMax = Math.max(yMax, dataMax + buffer);
				} else {
					// 无完整规格限时使用3-sigma统计法
					const mean = validValues.reduce((sum, val) => sum + val, 0) / validValues.length;
					const variance = validValues.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / validValues
						.length;
					const stdDev = Math.sqrt(variance) || 1; // 避免标准差为0的情况

					// 基础范围（3-sigma）
					if (yMin === null) yMin = mean - 3 * stdDev;
					if (yMax === null) yMax = mean + 3 * stdDev;

					// 确保包含所有数据点并添加缓冲
					yMin = Math.min(yMin, dataMin - buffer);
					yMax = Math.max(yMax, dataMax + buffer);

					// 特殊情况处理：数据全部为非负数时Y轴起点不小于0
					if (dataMin >= 0 && yMin < 0) {
						yMin = 0;
					}
				}

				// 确保Y轴范围不会过小（至少为数据范围的1.5倍或最小阈值）
				const minAllowedRange = Math.max(dataRange * 1.5, 0.1); // 最小允许范围
				if (yMax - yMin < minAllowedRange) {
					const center = (yMin + yMax) / 2;
					yMin = center - minAllowedRange / 2;
					yMax = center + minAllowedRange / 2;
				}

				// 保留3位小数精度
				return {
					format: val => val.toFixed(3),
					data: [{
						min: +yMin.toFixed(3),
						max: +yMax.toFixed(3),
						tofix: 2
					}]
				};
			},

			// 计算极差图Y轴范围（保持原有逻辑）
			calculateRangeYAxisOptions(values) {
				// 计算基本统计量
				const mean = values.reduce((sum, val) => sum + val, 0) / values.length;
				const variance = values.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / values.length;
				const stdDev = Math.sqrt(variance);

				// 计算合理的Y轴范围（使用3-sigma原则，从0开始）
				let yMax = mean + 3 * stdDev;

				// 确保Y轴范围不会太窄
				const minRange = stdDev * 2;
				if (yMax < minRange) {
					yMax = minRange;
				}

				// 格式化显示精度
				return {
					format: val => val.toFixed(3),
					data: [{
						min: 0,
						max: +yMax.toFixed(3),
						tofix: 2
					}]
				};
			},

			onMeanChartIndex(e) {
				const index = e.currentIndex.index;
				// if (typeof index === "number") {
				//     this.$refs.rangeChart.showToolTip(index);
				// }
			},
			onRangeChartIndex(e) {
				const index = e.currentIndex.index;
				// if (typeof index === "number") {
				//     this.$refs.meanChart.showToolTip(index);
				// }
			}
		}
	};
</script>

<style scoped>
	.spc-xr-chart {
		display: flex;
		flex-direction: column;
		padding: 20rpx;
	}

	qiun-data-charts {
		margin-bottom: 40rpx;
		background: #fff;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
	}
</style>